/*  回调函数不易维护管理，不能确定什么时候被触发，
    所以使用promise转换callback */
const http = require('http')

/*设置监听的端口*/
const port = 3000;

const server = http.createServer(async (req, res) => {
    /*从client获取数据*/
    const msg = await new Promise(((resolve, reject) => {
        const bufs = [];
        req.on('data', (buf) => {
            bufs.push(buf)
        });
        req.on('error', (err) => {
            reject(err)
        })
        req.on('end', () => {
            const buf = Buffer.concat(bufs).toString('utf8')
            let msg = 'hello';
            try {
                const ret = JSON.parse(buf)
                msg = ret.msg;
            } catch (err) {
                //res.end('invalid json')
            }
            resolve(msg)

        })
    }))

    /*response*/
    const responseJson = {
        msg: `receive your msg:${msg}`
    }
    res.setHeader('Content-Type', 'application/json')
    res.end(JSON.stringify(responseJson))


})

server.listen(port, () => {
    console.log("listening on:", port)
})